import React, { useState, useEffect } from 'react';
import { Table, Card, Button, message, Spin } from 'antd';
import { Link } from 'react-router-dom';
import apiService from '../services/apiService';

const UserList = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  const fetchUsers = async (page = 0, pageSize = 10) => {
    setLoading(true);
    try {
      const response = await apiService.getUserList(page, pageSize);
      if (response && response['[]']) {
        // 将用户数据转换为表格需要的格式
        const userData = response['[]'].map(item => ({
          ...item.User,
          key: item.User.id
        }));
        setUsers(userData);
        
        // 更新分页信息
        if (response.total) {
          setPagination({
            ...pagination,
            total: response.total
          });
        }
      }
    } catch (error) {
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  const handleTableChange = (pagination) => {
    fetchUsers(pagination.current - 1, pagination.pageSize);
    setPagination(pagination);
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      render: (sex) => sex === 0 ? '男' : '女'
    },
    {
      title: '标签',
      dataIndex: 'tag',
      key: 'tag',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button type="primary" size="small">
          <Link to={`/users/${record.id}`}>查看详情</Link>
        </Button>
      ),
    },
  ];

  return (
    <Card title="用户列表">
      <Spin spinning={loading}>
        <Table 
          columns={columns} 
          dataSource={users}
          pagination={pagination}
          onChange={handleTableChange}
        />
      </Spin>
    </Card>
  );
};

export default UserList; 